# -*- coding: UTF-8 -*-
"""
@Project : FastTortoiseDemo
@File    : .py
@IDE     : PyCharm
@Author  : xuan
@Date    : 2023/12/29 11:46
"""
from passlib.context import CryptContext
from fastapi import HTTPException
from tortoise.exceptions import DoesNotExist, IntegrityError
from Apps.user.user_models import User
from Apps.user.user_schemas import UserCreateSchema, UserLoginSchema, UserUpdateSchema, UserOut
from starlette import status

pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto", default="bcrypt")


class UserService:
    @staticmethod
    async def get_all_users():
        """
        获取全部的用户
        :return:
        """
        try:
            return await User.all()
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e)) from e

    @staticmethod
    async def get_user(user_id: int):
        try:
            return await User.filter(id=user_id).values()
        except Exception as e:
            raise HTTPException(status_code=500, detail=str(e)) from e

    @staticmethod
    async def create_user(user_data: UserCreateSchema):
        """
        创建用户
        :param user_data:
        :return:
        """
        if await User.filter(username=user_data.username).exists():
            return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="此用戶已存在")
        hashed_password = pwd_context.hash(user_data.password)

        try:
            user = await User.create(username=user_data.username, password=hashed_password)
            return UserOut(id=str(user.id), username=user.username)
        except IntegrityError as e:
            return HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

    @staticmethod
    async def login_user(user_data: UserLoginSchema):
        """
        检查用户是否存在并验证密码
        :param user_data:
        :return:
        """
        try:
            user = await User.get(username=user_data.username)
        except DoesNotExist as e:
            raise HTTPException(status_code=404, detail="未找到用户") from e

        if not pwd_context.verify(user_data.password, user.password):
            raise HTTPException(status_code=400, detail="无效的密码")

        await user.save()
        return user

    @staticmethod
    async def logout_user(user_id: int):
        """
        退出登录
        :param user_id:
        :return:
        """
        try:
            user = await User.get(id=user_id)
        except DoesNotExist as e:
            raise HTTPException(status_code=404, detail="未找到用户") from e

        await user.save()
        return user

    @staticmethod
    async def update_user(user_id: int, updated_user: UserUpdateSchema):
        """
        更新用户信息
        :param user_id:
        :param updated_user:
        :return:
        """
        try:
            user = await User.get(id=user_id)
        except DoesNotExist as e:
            raise HTTPException(status_code=404, detail="未找到用户") from e

        user.username = updated_user.username
        user.password = pwd_context.hash(updated_user.password)
        await user.save()
        return user

    @staticmethod
    async def delete_user(user_id: int):
        """
        删除用户
        :param user_id:
        :return:
        """
        try:
            user = await User.filter(id=user_id).first()

            if user is None:
                raise HTTPException(status_code=404, detail="未找到用户")
            user.is_deleted = 1  # 将用户状态设置为已删除
            await user.save()
            return {"message": "用户删除成功"}
        except DoesNotExist as e:
            raise HTTPException(status_code=500, detail=str(e)) from e
